from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from rss_reader.database.models import Base
from rss_reader.logger import logger
from pathlib import Path
import os

def get_db_path():
    """获取数据库绝对路径"""
    # 获取应用数据目录
    if os.name == 'nt':  # Windows
        app_data_dir = Path(os.getenv('APPDATA')) / 'PyQtRSSReader'
    else:  # Linux/Mac
        app_data_dir = Path.home() / '.config' / 'PyQtRSSReader'

    # 创建目录(如果不存在)
    app_data_dir.mkdir(parents=True, exist_ok=True)

    # 返回数据库绝对路径
    return str(app_data_dir / 'rss_reader.db')

def init_db(db_path=None):
    if not db_path:
        db_path = get_db_path()
    try:
        db_url = f'sqlite:///{db_path}'

        logger.info(f"初始化数据库连接: {db_url}")
        engine = create_engine(db_url)

        logger.debug("创建数据库表(如果不存在)")
        Base.metadata.create_all(engine)

        logger.debug("创建scoped session工厂")
        return scoped_session(sessionmaker(bind=engine))

    except Exception as e:
        logger.error(f"数据库初始化失败: {str(e)}", exc_info=True)
        raise